import hashlib
import uuid

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse

from App.models import MainWheel, MainNav, MainMustBuy, MainShop, MainShow, GoodsType, Goods, User, CartModel, OrdModel, \
    GoodsOrder


def home(request):
    wheels = MainWheel.objects.all()
    navs = MainNav.objects.all()
    mustbuys = MainMustBuy.objects.all()
    shops = MainShop.objects.all()
    shop_1 = shops[0]
    shop_2_3 = shops[1:3]
    shop_4_7 = shops[3:7]
    shop_8_11 = shops[7:11]
    shows = MainShow.objects.all()
    data = {
        'title': '首页',
        'wheels': wheels,
        'navs': navs,
        'mustbuys': mustbuys,
        'shop_1': shop_1,
        'shop_2_3': shop_2_3,
        'shop_4_7': shop_4_7,
        'shop_8_11': shop_8_11,
        'shows': shows,

    }
    return render(request, 'home/home.html', context=data)


def market(request):
    return redirect(reverse('axf:marketParams', args=("104749", '0', '0')))


def marketParams(request, typeid, cid, sort_rule):
    goodstypes = GoodsType.objects.all()
    # 找到类型分类id对应的goodstype
    goodstype_currents = GoodsType.objects.filter(typeid=typeid)
    # 子类的类别列表
    child_type_list = []
    if goodstype_currents.exists():
        # 获取到传进来的类别对象信息
        goodstype = goodstype_currents.first()
        # 子类,字符串数据
        childtypes = goodstype.childtypenames
        childtypenames = childtypes.split("#")
        for child_type_name in childtypenames:
            # 子类的分类名字，及其关联的商品id信息
            type_list = child_type_name.split(':')
            # 将分类数据追加进去，这样可以获取到每一个大类对应的子类信息
            child_type_list.append(type_list)
    # 对路径参数中的cid，进行判断，查找响应的商品数据
    if cid == '0':  # 表示的是全部商品
        goods_list = Goods.objects.filter(categoryid=typeid)
        # typeid 和 categoryid   并且是一对多的一个关系
    else:
        goods_list = Goods.objects.filter(categoryid=typeid).filter(childcid=cid)
    if sort_rule == "0":
        pass
    elif sort_rule == "1":
        goods_list = goods_list.order_by("productnum")
    elif sort_rule == "2":
        goods_list = goods_list.order_by("-price")
    elif sort_rule == "3":
        goods_list = goods_list.order_by("price")
    data = {
        'title': '闪购',
        'goodstypes': goodstypes,
        'goods_list': goods_list,
        'typeid': typeid,
        'child_type_list': child_type_list,
        'cid': cid,
    }
    return render(request, 'market/market.html', context=data)


def cart(request):
    userid = request.session.get('user_id')
    if not userid:
        return redirect(reverse('axf:userlogin'))
    else:
        # 将用户的购物车数据全部获取到,计算总金额
        carts = CartModel.objects.filter(is_select=True)
        money = 0
        for cart in carts:
            num = cart.goods.price * cart.c_num
            money += num
        carts = CartModel.objects.filter(user_id=userid)
    all_carts = CartModel.objects.all()
    is_all_select = True
    for cartt in all_carts:
        if not cartt.is_select:
            is_all_select = False
        break
    data = {
        'title': '购物车',
        'carts': carts,
        'money': money,
        'is_all_select': is_all_select,
    }
    return render(request, 'cart/cart.html', context=data)


# 我的  界面
def mine(request):
    user_id = request.session.get('user_id')
    data = {
        'title': '我的',
    }
    if user_id:
        users = User.objects.filter(pk=user_id)
        if users.exists():
            user = users.first()
            username = user.username
            # 图片地址
            icon = "/static/uploads/" + user.icon.url
            data["username"] = username
            data["icon"] = icon
            data["is_login"] = True
            has_pay = 0
            not_pay = 0
            orders = user.ordmodel_set.all()
            for order in orders:
                if order.o_status == 0:
                    not_pay += 1
                elif order.o_status == 1:
                    has_pay += 1
                elif order.o_status == 2:
                    pass
            data['has_pay'] = has_pay
            data['not_pay'] = not_pay
    return render(request, 'mine/mine.html', context=data)


# 用户注册
def user_register(request):
    if request.method == 'GET':
        return render(request, 'user/user_register.html')
    else:
        try:
            username = request.POST.get('username')
            email = request.POST.get('email')
            password = request.POST.get('password')
            icon = request.FILES.get('icon')
            user = User()
            user.username = username
            user.email = email
            user.password = reload_psw(password)
            user.icon = icon
            user.save()
            return redirect(reverse('axf:mine'))
        except Exception as e:
            # return redirect(reverse('axf:register'))
            return HttpResponse(e)


# 密码的数据二次安全
def reload_psw(password):
    sha = hashlib.sha512()
    sha.update(password.encode())
    return sha.hexdigest()


# 验证用户名是否已经存在
def check_name(request):
    username = request.GET.get('username')
    user = User.objects.filter(username=username)
    data = {
        "msg": "ok",
        "status": "200",
    }
    if user.exists():
        data["desc"] = "用户已存在"
        data["msg"] = "fail"
        data["status"] = "900"
    else:
        data["desc"] = "用户名可用"
    return JsonResponse(data)


# 用户登录
def user_login(request):
    if request.method == 'GET':
        return render(request, 'user/user_login.html')
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(reload_psw(password))
        from django.db.models import Q
        users = User.objects.filter(Q(username=username) | Q(email=username))
        if users.exists():
            user = users.first()
            if user.password == reload_psw(password):
                # 验证登录成功，设置session
                request.session['user_id'] = user.id
                return redirect(reverse('axf:mine'))
        return redirect(reverse('axf:userlogin'))


# 退出
def user_logout(request):
    request.session.flush()
    return redirect(reverse('axf:mine'))


# 向购物车数据中添加数据
def add_cart(request):
    # 获取到商品id
    goods_id = request.GET.get('goods_id')
    # 获取用户信息
    user_id = request.session.get('user_id')
    data = {
        'msg': 'ok',
        'status': '200',
    }
    if not user_id:
        data['status'] = '910'
        data['msg'] = '未登录'
    else:
        carts = CartModel.objects.filter(goods_id=goods_id)
        if carts.exists():
            cart = carts.first()
            cart.c_num += 1
            cart.save()
            data['g_num'] = cart.c_num
        else:
            cart = CartModel()
            cart.user_id = user_id
            cart.goods_id = goods_id
            cart.save()
            data['g_num'] = cart.c_num
    return JsonResponse(data)


def sub_cart(request):
    # 获取到商品id
    goods_id = request.GET.get('goods_id')
    # 获取用户信息
    user_id = request.session.get('user_id')
    data = {
        'msg': 'ok',
        'status': '200',
    }
    if not user_id:
        data['status'] = '910'
        data['msg'] = '未登录'
    else:
        carts = CartModel.objects.filter(goods_id=goods_id)
        if carts.exists():
            cart = carts.first()
            if cart.c_num == 1:
                cart.delete()
                data['g_num'] = 0
            else:
                cart.c_num -= 1
                cart.save()
                data['g_num'] = cart.c_num
        else:
            data['g_num'] = 0
            data['status'] = '911'
            data['msg'] = 'cart not exist'
    return JsonResponse(data)


# 点击改变商品选中状态的视图函数
def change_selected(request):
    cartid = request.GET.get('cartid')
    data = {
        'msg': 'ok',
        'status': '200',
        'money': 0,
    }
    cart = CartModel.objects.get(pk=cartid)
    cart.is_select = not cart.is_select
    cart.save()
    money = 0
    carts = CartModel.objects.filter(is_select=True)
    if carts.exists():
        for cart1 in carts:
            num = cart1.goods.price * cart.c_num
            money += num
        data['money'] = money
    else:
        pass
    data['is_select'] = cart.is_select
    return JsonResponse(data)


def sub_to_cart(request):
    cartid = request.GET.get('cartid')
    cart = CartModel.objects.get(pk=cartid)
    data = {
        'msg': 'ok',
        'status': '200',
        'money': 0,
    }
    if cart.c_num == 1:
        cart.delete()
        data['g_num'] = 0
        data['status'] = '912'
    else:
        cart.c_num -= 1
        cart.save()
        data['g_num'] = cart.c_num
    money = 0
    carts = CartModel.objects.filter(is_select=True)
    for cart2 in carts:
        num = cart2.goods.price * cart2.c_num
        money += num
    data['money'] = money
    return JsonResponse(data)


def all_select(request):
    # 获取到的是字符串的数据
    selects = request.GET.get('selects')
    action = request.GET.get('action')
    select_list = selects.split('#')
    # print(select_list)
    data = {
        'msg': 'ok',
        'status': '200',
        'money': 0,
    }
    if action == 'unselect':
        for select in select_list:
            cart = CartModel.objects.get(pk=select)
            cart.is_select = False
            cart.save()
    else:
        money = 0
        for select in select_list:
            cart = CartModel.objects.get(pk=select)
            cart.is_select = True
            cart.save()
        carts = CartModel.objects.filter(is_select=True)
        for cart2 in carts:
            num = cart2.goods.price * cart2.c_num
            money += num
        data['money'] = money
        # print(data['money'])
    return JsonResponse(data)


def add_to_cart(request):
    cartid = request.GET.get('cartid')
    cart = CartModel.objects.get(pk=cartid)
    data = {
        'msg': 'ok',
        'status': '200',
        'money': 0,
    }
    cart.c_num += 1
    cart.save()
    money = 0
    carts = CartModel.objects.filter(is_select=True)
    for cart2 in carts:
        num = cart2.goods.price * cart2.c_num
        money += num
    data['money'] = money
    data['g_num'] = cart.c_num
    return JsonResponse(data)


# 创建订单，并有支付按钮
def genarate_order(request):
    selects = request.GET.get('selects')
    user_id = request.session.get('user_id')
    order = OrdModel()
    order.user_id = user_id
    order.o_num = str(uuid.uuid4())
    order.save()
    select_list = selects.split('#')
    for select in select_list:
        cart = CartModel.objects.get(pk=select)
        goods_order = GoodsOrder()
        goods_order.goods_id = cart.goods_id
        goods_order.nums = cart.c_num
        goods_order.order_id = order.id
        goods_order.save()
        #     订单创建好了之后要把cart表里选中的数据删掉
        cart.delete()
    data = {
        'msg': 'ok',
        'status': '200',
        'order_id': order.id,
    }
    return JsonResponse(data)


def order_info(request, orderid):
    order = OrdModel.objects.get(pk=orderid)
    data = {
        'order': order,
    }
    return render(request, 'order/order_info.html', context=data)


# 支付成功之后改变订单的状态码
def change_status(request):
    order_id = request.GET.get('order_id')
    order = OrdModel.objects.get(pk=order_id)
    order.o_status = 1
    order.save()
    data = {
        'status': '200',
        'msg': 'ok',
    }
    return JsonResponse(data)


# 未付款的订单页面
def not_pay_order(request):
    user_id = request.session.get('user_id')
    orders = OrdModel.objects.filter(user_id=user_id).filter(o_status=0)
    data = {
        'orders': orders,
    }
    return render(request, 'order/not_pay_order.html', context=data)


def has_pay_order(request):
    user_id = request.session.get('user_id')
    orders = OrdModel.objects.filter(user_id=user_id).filter(o_status=1)
    data = {
        'orders': orders,
    }
    return render(request, 'order/has_pay_order.html', context=data)
